//
//  QCCheckController.swift
//  爱汽车
//
//  Created by tucici on 2023/12/31.
//

import UIKit
import TCCKit
enum QCCheckMode{
    case auto(_ title:String, _ status:Int, _ error:[String])
    case manual(_ title:String,_ bytes:[UInt8], _ subTitle:String)
}
class QCCheckController: QCViewController {
    private var logoR : UIImageView!
    private var logoL : UIImageView!
    private var page : UIPageControl!
    private var okBtn : UIButton!
    private var array = [QCCheckMode]()
    private var errors = [String]()
    private var titles = ["检测最低高度","检测车身水平状态","检测传感器","检测最高高度","检测线束状态","检测动态调整"]
    ///手动模式下，没有保存前一次的原始数据，手动检测完毕后，要数据要复原
    private var oldBytes = [UInt8]()
    var isAuto = true
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        oldBytes = base_info
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
    override func initUI() {
        backBtn?.isHidden = false
        logoR = UIImageView(image: UIImage(named: "自检logo"))
        logoL = UIImageView(image: UIImage(named: "自检左边logo"))
        view.addSubview(logoR)
        view.addSubview(logoL)
        
        flowLayout.scrollDirection = .horizontal
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isPagingEnabled = true
        collectionView.backgroundColor = .clear
        collectionView.isScrollEnabled = false
        collectionView.register(QCAutoCheckCell.nib(), forCellWithReuseIdentifier: QCAutoCheckCell.ID())
        collectionView.register(QCManualCheckCell.nib(), forCellWithReuseIdentifier: QCManualCheckCell.ID())
        collectionView.register(QCCheckResultCell.self, forCellWithReuseIdentifier: QCCheckResultCell.ID())
        view.bringSubviewToFront(collectionView)
        
        page = UIPageControl()
        page.backgroundColor = .clear
        page.numberOfPages = 6
        page.currentPage = 0
        page.isUserInteractionEnabled = false
        page.currentPageIndicatorTintColor = "#FF4E00".color()
        page.isHidden = true
        view.addSubview(page)
        
        okBtn = UIButton(type: .custom)
        okBtn.isHidden = true
        okBtn.setTitle(LS("确定"), for: .normal)
        okBtn.cornerRadius = 18
        okBtn.bgHexColor = "#FF4B00"
        okBtn.textHexColor = "#FFFFFF"
        okBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        okBtn.addTarget(self, action: #selector(actionForOK), for: .touchUpInside)
        view.addSubview(okBtn)
        
        logoR.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 169, height: 146))
            make.top.equalToSuperview()
            make.right.equalToSuperview().offset(38)
        }
        
        logoL.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 169, height: 146))
            make.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(-38)
        }
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        page.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview().inset(60)
            make.height.equalTo(30)
        }
        
        okBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 109, height: 38))
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().inset(40+LLBottomInset)
        }
    }
    
    override func initData() {
        super.initData()
        for i in 0..<titles.count{
            let fitler = (i == 0 && isAuto == false) || (i == 3 && isAuto == false)
            let subtitle = i == 0 ? "请设定最低高度\n设置完成后请点击保存" : "请设定最高高度\n设置完成后请点击保存"
            let model:QCCheckMode = fitler ? .manual("\(i+1)/\(titles.count) "+LS(titles[i]), [UInt8](),subtitle) : .auto("\(i+1)/\(titles.count) "+LS(titles[i]), 2, [String()])
            array.append(model)
        }
        let successModel = QCCheckMode.auto("", 2, [String]())
        array.append(successModel)
        collectionView.reloadData()
    }
    
    override var base_info: [UInt8]{
        didSet{
            currentBytes = base_info
        }
    }
    
    override var bytes: [UInt8]{
        didSet{
            currentBytes = bytes
        }
    }
    private var currentBytes = [UInt8](){
        didSet{
            guard currentBytes.count >= 8 else{return}
            let ack = currentBytes[7]
            let data = [UInt8](currentBytes[AI_index..<currentBytes.count])
            switch (ack){
            case (UInt8(AIQC.infoStatus.ack)):
                let workMode = Int(data[0])
                let step = Int(data[1])
                if step <= 0 {return}
                ///根据0x90的检测上传
                ///1， 如果是自动模式，完成后，自动滚动
                ///2， 如果是手动模式，第2，3，5，6，是完成状态，自动滚动
                //if (workMode == 1 || (workMode == 2 && step != 1 && step != 4)) {
                nextRow = step
                //}
                ///解析手动模式，调整的参数
                if workMode == 2, case let .manual(title, _, subtitle) = array[step-1] {
                    array[step-1] = .manual(title, currentBytes,subtitle)
                }
                ///手动模式，第1，4步，隐藏page
                page.isHidden = workMode == 2 && (step == 1 || step == 4)
                let s = data.map{String(format: "%.2X ", $0)}.joined()
                print("?????????? 模式 = \(workMode == 1 ? "自动":"手动") == 第\(step)")
            case (UInt8(AIQC.autoCheckUp.ack)):
                let status = Int(data[2])///0:失败;1:成功；2:正在进行
                let error = Int(data[3])///错误代码
                if error > 0 && error <= 20 {errors.append(errorStr(error)) }
                for i in 0..<array.count{
                    let index = status == 0 ? i : nextRow - 1
                    let mode = array[index]
                    switch mode{
                    case let .auto(title, _, _):
                        array[index] = .auto(title, status, errors)
                    case let .manual(title, _, subtitle):
                        array[index] = .manual(title, currentBytes, subtitle)
                    }
                    if status != 0{ break}
                }
                if error > 0 || nextRow == 6{
                    okBtn.isHidden = false
                    page.isHidden = true
                }
                let s = data.map{String(format: "%.2X ", $0)}.joined()
                //print("==========\(s)")
            default:
                break
            }
            collectionView.reloadData()
        }
    }
    
    private var nextRow = 1{
        didSet{
            if array.count < nextRow{return}
            if page.currentPage + 1 >= nextRow {return}
            page.currentPage = nextRow - 1
            collectionView.setContentOffset(CGPoint(x: kUIScreenWidth * CGFloat(nextRow - 1), y: 0), animated: false)
        }
    }
    override func backBtnAction() {
        alert("注意","是否确定退出",nil,{[weak self] in
            self?.actionForOK()
        })
    }
    
    func action(_ title:String, _ index:IndexPath?){
        switch title {
        case LS("退出"):///系统检测停止
            actionForOK()
        case LS("保存"):
            switch nextRow {
            case 1:///1/6手动检测模式下，设置最低高度
                BLEData.appSetDataToPer(AIQC.setHightToMin.cmd, "00").write
            case 4:///4/6手动检测模式下，设置最高高度
                BLEData.appSetDataToPer(AIQC.setHightToMax.cmd, "00").write
            default:
                break
            }
            nextRow += 1///手动模式下，第1，4，步保存后，手动滚到下页
        default:
            break
        }
    }
    
    @objc func actionForOK(){
        BLEData.appSetDataToPer(AIQC.systemCheckEnd.cmd, "00").write
        if errors.count  <= 0{
            CCHud.start(LS("请稍后..."), stopTime: 1.5) {[weak self] in
                guard let self = self else{return}
                navigationController?.popToRootViewController(animated: true)
            }
            return
        }
        let vc = QCCheckResultController()
        vc.array = titles
        vc.errors = errors
        navigationController?.pushViewController(vc, animated: true)
    }
    
    private func errorStr(_ code:Int)->String{
        let error_arr = ["电池电压异常","ACC未启动",
                         "气罐气压传感器故障","自检超时",
                         "左前高度传感器超量程","右前高度传感器超量程",
                         "左后高度传感器超量程","右后高度传感器超量程",
                         "左前气压传感器故障","右前气压传感器故障",
                         "左后气压传感器故障","右后气压传感器故障",
                         "左前高度传感器故障","右前高度传感器故障",
                         "左后高度传感器故障","右后高度传感器故障",
                         "左前高度传感器测量范围过小","右前高度传感器测量范围过小",
                         "左后高度传感器测量范围过小","右后高度传感器测量范围过小",
                         "左前高度传感器线序错误","右前高度传感器线序错误",
                         "左后高度传感器线序错误","右后高度传感器线序错误"]
        return code - 1 >= error_arr.count ? "" : error_arr[code-1]
    }
}
//MARK: - UICollectionViewDataSource
extension QCCheckController:UICollectionViewDataSource
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = array[indexPath.row]
        switch model{
        case .auto(_, _, _):
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier:QCAutoCheckCell.ID(), for:indexPath) as! QCAutoCheckCell
            cell.model = model
            return cell
        case .manual(_, _, _):
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier:QCManualCheckCell.ID(), for:indexPath) as! QCManualCheckCell
            cell.model = model
            cell.block = {[weak self] text in
                self?.action(text, indexPath)
            }
            return cell
        }
    }
}
//MARK: - UICollectionViewDelegate
extension QCCheckController:UICollectionViewDelegate
{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
        
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        page.currentPage = Int(scrollView.contentOffset.x / kUIScreenWidth)
    }
}
//MARK: - UICollectionViewDelegateFlowLayout
extension QCCheckController:UICollectionViewDelegateFlowLayout
{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
        return  CGSize(width:kUIScreenWidth , height: kUIScreenHeight - kUINavigationBarHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
        return 0
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return .zero
    }
}
